import Client from './client';
import * as qiniu from 'qiniu-js';
import {computeMd5, getFileSuffix} from '../utils/helper';

export default class Kodo extends Client{
    run(callback) {
        const {file, id, config} = this;
        const {onProgress, onSuccess, onError} = callback;

        /* "path/to/file_name.ext" */
        const key = `${config.uploadDate}${computeMd5(file)}.${getFileSuffix(file)}`;
        const observable = qiniu.upload(file, key, config.token);

        const observer = {
            complete: (data) => onSuccess({id, data: {...data, host: config.host, ispType: 'qiNiu'}}),
            error: (info) => onError({id, info}),
            next: (progress) => onProgress({id, progress: {percent: progress.total.percent}}),
        };

        this.subscription = observable.subscribe(observer);
    }
    
    abort() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
